package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import cn.wolfcode.luowowo.cache.util.RedisKeys;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

/**
 * Created by admin on 2019/8/7.
 */
@Controller
public class LoginController {

    @Reference
    private IUserInfoService userInfoService;

    // 验证电话号码是否存在
    @RequestMapping("/checkPhone")
    @ResponseBody
    public Object login(String phone) {

        return !userInfoService.selectCountByPhone(phone);
    }

    // 发送验证码
    @RequestMapping("/sendVerifyCode")
    @ResponseBody
    public Object sendVerifyCode(String phone) {
        AjaxResult result = new AjaxResult();
        try {
            userInfoService.sendVerifyCode(phone);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, e.getMessage());
        }
        return result;
    }


    // 用户注册
    @RequestMapping("/userRegist")
    @ResponseBody
    public Object userRegist(String phone, String nickname, String password, String rpassword, String verifyCode) {
        userInfoService.userRegist(phone, nickname, password, rpassword, verifyCode);
        return AjaxResult.SUCCESS;
    }

    // 用户登录
    @RequestMapping("/userLogin")
    @ResponseBody
    public Object userLogin(HttpServletResponse response, String username, String password) {

        // 返回 token
        String token = userInfoService.userLogin(username, password);

        // 将用户登录信息存入到 cookie中
        CookieUtil.setCookie(response, "token", token, RedisKeys.USER_LOGIN_TOKEN.getTimeout().intValue());

        return AjaxResult.SUCCESS;
    }

    // 用户信息注入
    @RequestMapping("/userInfo")
    @ResponseBody
    public UserInfo userLogin(@UserParam UserInfo userInfo) {
        return userInfo;
    }
}
